package com.linkoog.devtools.intellij.ui;

import com.intellij.icons.AllIcons;
import com.intellij.ui.TitledSeparator;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.components.BorderLayoutPanel;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class HideableSection extends BorderLayoutPanel {

    private boolean isExpanded = false;

    private String title;
    private JComponent component;

    private TitledSeparator titledSeparator;
    private BorderLayoutPanel contentPanel;


    public HideableSection(String text, JComponent component) {
        this.title = text;
        this.component = component;
        titledSeparator = new TitledSeparator(text);
        titledSeparator.getLabel().setCursor(new Cursor(Cursor.HAND_CURSOR));

        contentPanel = new BorderLayoutPanel();
        contentPanel.setBorder(JBUI.Borders.emptyLeft(20));

        addToTop(titledSeparator);
        addToCenter(contentPanel);

        updateComponent(component);
        titledSeparator.addMouseListener( new MouseAdapter() {
            @Override
            public void mouseReleased(MouseEvent e) {
                update(!isExpanded);
            }
        });
    }

    public void updateTitleAndComponent(String newTitle, JComponent newComponent) {
        titledSeparator.setText(newTitle);
        updateComponent(newComponent);
    }

    private void updateComponent(JComponent newComponent) {
        component = newComponent;
        contentPanel.removeAll();
        contentPanel.addToCenter(newComponent);
        update(isExpanded);
    }

    private void update(Boolean isExpanded) {
        this.isExpanded = isExpanded;
        contentPanel.setVisible(isExpanded);
        titledSeparator.getLabel().setIcon(isExpanded ?  AllIcons.General.ArrowDown : AllIcons.General.ArrowRight);
    }

}
